// 引入zustand库和Immer中间件
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';

type UserInfo = {
  username: string
  avatar: string
  hobby: string[]
}

type Action = {
  updateToken: (token: string) => void
  updateUserInfo?: (userInfo: UserInfo) => void
  updateUserName: (username: string) => void
  updateUserHoby: (arr: string[]) => void
  resetHoby: () => void
  updateUserHoby2: () => void
}

interface State {
  token: string
  userInfo: UserInfo
}

// 创建带有Immer中间件的zustand存储
// eslint-disable-next-line function-paren-newline
export const useUserStore = create<State & Action>()(

  // 这里使用了immer进行包裹住“设置函数”（setter）
  immer(set => ({
    token: '',
    userInfo: { username: 'xxx', avatar: 'http://xxxx.com/yy.jpg', hobby: ['1', '2', '4', '5'] },
    updateToken: token => set(state => {
      state.token = token;
    }),
    updateUserName: username => set(state => {
      state.userInfo.username = username;
    }),
    updateUserHoby: arr => set(state => {
      state.userInfo.hobby = state.userInfo.hobby.concat(arr)
    }),
    updateUserHoby2: () => set(state => {
      state.userInfo.hobby.push('333');
    }),
    resetHoby: () => set(state => {
      state.userInfo.hobby = ['1', '2', '4', '5']
    })
  })));

